# 极简Windows守护进程 - 专注于稳定性
import os
import sys
import time
import subprocess
import signal
import traceback

# 设置代码页以支持中文输出
os.system('chcp 65001 > nul 2>&1')

# 获取脚本所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)

# 虚拟环境路径
venv_path = os.path.join(script_dir, 'venv')
venv_python = os.path.join(venv_path, 'Scripts', 'python.exe')

# 辅助函数：打印带时间戳的消息
def log(message):
    timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
    print(f'[{timestamp}] {message}', flush=True)

# 初始化虚拟环境
def init_environment():
    log('=== 初始化环境 ===')
    
    # 检查虚拟环境是否存在
    if not os.path.exists(venv_path):
        log('创建虚拟环境...')
        try:
            subprocess.run([sys.executable, '-m', 'venv', venv_path], shell=False)
            log('虚拟环境创建完成')
        except Exception as e:
            log(f'创建虚拟环境失败: {str(e)}')
            return False
    
    # 检查虚拟环境Python是否存在
    if not os.path.exists(venv_python):
        log(f'错误: 虚拟环境Python不存在: {venv_python}')
        return False
    
    # 安装必要的包
    log('安装Flask依赖...')
    try:
        # 基本安装Flask
        subprocess.run([venv_python, '-m', 'pip', 'install', 'flask'], 
                      stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        log('Flask安装完成')
        return True
    except Exception as e:
        log(f'安装依赖失败: {str(e)}')
        return False

# 清理进程
def cleanup_process(process):
    if process and process.poll() is None:
        log('清理运行中的进程...')
        try:
            process.terminate()
            process.wait(timeout=2)
            log('进程已终止')
        except:
            log('强制终止进程')
            try:
                process.kill()
            except:
                pass

# 主循环
def main():
    log('====== Windows守护进程启动 ======')
    log('目标: 确保Flask服务持续运行')
    log('访问地址: http://localhost:8000')
    log('按 Ctrl+C 停止')
    
    # 初始化环境
    if not init_environment():
        log('环境初始化失败，3秒后退出...')
        time.sleep(3)
        return
    
    restart_count = 0
    current_process = None
    
    try:
        while True:
            restart_count += 1
            log(f'[重启 {restart_count}] 启动服务...')
            
            # 设置环境变量
            env = os.environ.copy()
            env['FLASK_APP'] = 'main.py'
            env['FLASK_ENV'] = 'production'
            env['PYTHONUNBUFFERED'] = '1'
            
            try:
                # 直接运行main.py脚本
                current_process = subprocess.Popen(
                    [venv_python, 'main.py'],
                    env=env,
                    shell=False,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT,
                    text=True
                )
                
                log(f'服务已启动，PID: {current_process.pid}')
                
                # 实时读取输出
                while True:
                    line = current_process.stdout.readline()
                    if line:
                        print(f'[Flask] {line.strip()}', flush=True)
                    elif current_process.poll() is not None:
                        break
                    else:
                        # 短暂休眠避免CPU占用过高
                        time.sleep(0.1)
                
                exit_code = current_process.poll()
                log(f'服务已退出，退出码: {exit_code}')
                
            except Exception as e:
                log(f'启动服务异常: {str(e)}')
                log(traceback.format_exc())
            finally:
                cleanup_process(current_process)
            
            # 等待2秒后重启
            log('2秒后重新启动服务...')
            time.sleep(2)
            
    except KeyboardInterrupt:
        log('接收到停止信号，正在退出...')
    finally:
        cleanup_process(current_process)
        log('守护进程已退出')

if __name__ == '__main__':
    main()